function payTypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "货到付款";
    else if (value == 2)
        return "微信支付";
    else if (value == 3)
        return "余额支付";
    else return ""
}

$("#mfile").fileinput({
    showPreview: true,
    showUpload: true,
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=order',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidpic").val(data.response.data);
})
$("#mfile2").fileinput({
    showPreview: true,
    showUpload: true,
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=order',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidpic2").val(data.response.data);
})

function statusFormatter(value, row, index) {
    console.log(">>>value=" + value)
    if (value === undefined || value.length == 0) return "";
    else if (value == -1)
        return "已取消";
    else if (value == 0)
        return "已关闭";
    else if (value == 1)
        return "待支付";
    else if (value == 2)
        return "待发货";
    else if (value == 3)
        return "待确认";
    else if (value == 4)
        return "待评价";
    else if (value == 5)
        return "已完成";
    else return ""
}

function orderTypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 0)
        return "默认";
    else if (value == 1)
        return "拼团";
    else if (value == 2)
        return "抽奖";
    else if (value == 4)
        return "砍价";
    else return ""
}

function timeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    return value.substr(5)
}

function gtypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "实物产品";
    else if (value == 2)
        return "虚拟产品";
    else if (value == 3)
        return "预约到店服务";
    else if (value == 4)
        return "预约上门服务";
    else return ""
}

function typeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 0)
        return "默认";
    else if (value == 0)
        return "自己买单";
    else if (value == 2)
        return "他人买单";
    else return ""
}

function changeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/order/list'});
        },
        dataType: "json"
    });
}

function changeStatus(id, status) {
    swal({
        title: '您确定要取消此订单吗？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定取消！',
        cancelButtonText: '取消关闭！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {

        $.ajax({
            type: 'POST',
            url: "/admin/order/cancel",
            data: {
                oid: id,
                status: status
            },
            success: function (e) {
                console.log(e)
                if (e.code == 0) {
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/order/list'});
                } else {
                    swal({title: "操作失败", text: e.msg, type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay', 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function shipperChange(id) {
    if (id == 3) {
        $('#shipperDiv').hide()
    } else {
        $('#shipperDiv').show()
    }
}

function deleteOne(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {

        $.ajax({
            type: 'POST',
            url: "deleteOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/order/list'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

var editsw = [];
/**
 * 为模态框填充数据
 */
$('#modal-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)

    modal.find('#id').val(data.id)
    modal.find('#gid').val(data.gid)
    modal.find('#orderNo').val(data.orderNo)
    modal.find('#refundNo').val(data.refundNo)
    modal.find('#couponId').val(data.couponId)
    modal.find('#shipperCode').val(data.shipperCode)
    modal.find('#shipperName').val(data.shipperName)
    modal.find('#address').val(data.address)
    modal.find('#linkman').val(data.linkman)
    modal.find('#phone').val(data.phone)
    modal.find('#payType').find("option[value='" + data['payType'] + "']").attr("selected", true);
    modal.find('#expire').val(data.expire)
    // 此部分需要注意：如果页面有两个以上的图片编辑
    // 该部分逻辑需要重写
    $("#mFile").fileinput('refresh', {
        initialPreview: [ //预览图片的设置
            "<img src='" + data.pic + "' class='file-preview-image' alt='' title=''>",
        ],
    });
    $("#previewPic").attr("src", data.pic);
    modal.find('#goodsName').val(data.goodsName)
    modal.find('#spec').val(data.spec)

    modal.find('#price').val(data.price)
    modal.find('#saleprice').val(data.saleprice)
    modal.find('#prices').val(data.prices)
    modal.find('#yunfei').val(data.yunfei)
    modal.find('#total').val(data.total)
    modal.find('#activityDiscount').val(data.activityDiscount)
    modal.find('#memberDiscount').val(data.memberDiscount)
    modal.find('#couponDiscount').val(data.couponDiscount)
    modal.find('#jifenDiscount').val(data.jifenDiscount)
    modal.find('#jifen').val(data.jifen)
    modal.find('#meid').val(data.meid)
    modal.find('#deduction').val(data.deduction)
    modal.find('#discount').val(data.discount)
    modal.find('#realpay').val(data.realpay)
    editsw["isNeedLogistics"] == undefined ? editsw["isNeedLogistics"] = new Switchery(document.querySelector('#isNeedLogistics'), {color: "#1AB394"}) : ""
    if (data.isNeedLogistics == 1) {
        setSwitchery(editsw["isNeedLogistics"], true);
    } else {
        setSwitchery(editsw["isNeedLogistics"], false);
    }
    modal.find('#yytime').val(data.yytime)
    modal.find('#status').find("option[value='" + data['status'] + "']").attr("selected", true);
    editsw["state"] == undefined ? editsw["state"] = new Switchery(document.querySelector('#state'), {color: "#1AB394"}) : ""
    if (data.state == 1) {
        setSwitchery(editsw["state"], true);
    } else {
        setSwitchery(editsw["state"], false);
    }
    modal.find('#orderType').find("option[value='" + data['orderType'] + "']").attr("selected", true);
    modal.find('#gtype').find("option[value='" + data['gtype'] + "']").attr("selected", true);
    modal.find('#traces').val(data.traces)
    modal.find('#goodsNumber').val(data.goodsNumber)
    modal.find('#serviceCode').val(data.serviceCode)
    editsw["isComment"] == undefined ? editsw["isComment"] = new Switchery(document.querySelector('#isComment'), {color: "#1AB394"}) : ""
    if (data.isComment == 1) {
        setSwitchery(editsw["isComment"], true);
    } else {
        setSwitchery(editsw["isComment"], false);
    }
    modal.find('#remark').val(data.remark)
    modal.find('#type').find("option[value='" + data['type'] + "']").attr("selected", true);
    modal.find('#pid').val(data.pid)

})

$('#kuaidi-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    $('#selectShipperMethod').find("option[value='" + data.shipperMethod + "']").attr("selected", true);
    $('#txtShipperCode').val(data.shipperCode);
    if (data.shipperMethod == 3 || data.shipperMethod == 4) {
        $('#shipperDiv').hide();
    } else {
        $('#shipperDiv').show();
    }
    console.log(data)

    modal.find('#hidid').val(data.id)
})

function fahuomodel(i, idx) {
    var pstype = rows[i].shipperMethod
    $('#selectShipperMethod').find("option[value='" + pstype + "']").attr("selected", true);
    $('#kuaidi-form').modal("show");
}

function fahuo() {
    console.log("............fahuo")
    console.log("............$(#hidid).val()=" + $("#hidid").val())
    console.log("............$(#selectShipperName).val()=" + $("#selectShipperName").val())
    console.log("............$(#txtShipperCode).val()=" + $("#txtShipperCode").val())
    $.ajax({
        type: 'POST',
        url: "fahuo",
        data: {
            id: $("#hidid").val(),
            shipperMethod: $("#selectShipperMethod").val(),
            shipperName: $("#selectShipperName").find("option:selected").text(),
            shipperCode: $("#selectShipperName").val(),
            yundanno: $("#txtShipperCode").val(),
            status: 3
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/order/list'});
            $('#kuaidi-form').modal('hide');
        },
        dataType: "json"
    });
}

//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 170;
}

var rows = []

function orderActionFormatter(value, row, index) {
    var status = row.status;
    var gtype = row.gtype;
    var id = row.id;
    rows[id] = row
    var res = ' ';
    // res += ' <button data-toggle="modal" class="btn-sm btn-primary"  data-row=' + id + ' data-index=' + index + '>订单详情</button>';
    if (status >= 1 && status <= 3)
        res += ' <button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-row=' + id + ' data-index=' + index + '>修改</button>';
    if (status > 1 && status <= 3)
        res += ' <button type="button" class="btn-sm btn-danger" onclick="changeStatus(\'' + id + '\',-1)" >取消订单</button>';
    if (status == 2 && gtype == 1) {
        res += ' <button data-toggle="modal" class="btn-sm btn-primary" href="list.html#kuaidi-form" data-row=' + id + ' data-index=' + index + '>发货</button>';
        // res +=' <button type="button" class="btn-sm btn-info" onclick="fahuomodel(\'' + id + '\',\'' + index + '\')" >发货</button>';
    }
    return res;
}

function goodActionFormatter(value, row, index) {
    var status = row.status;
    var id = row.id;
    var res = '<button data-toggle="modal" class="btn-sm btn-primary"  data-row=' + id + ' data-index=' + index + '>查看</button>';
    if (status >= 1 && status <= 3)
        res += ' <button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-id=' + id + ' data-index=' + index + '>修改</button>';
    if (status == 2)
        res += ' <button data-toggle="modal" class="btn-sm btn-primary" onclick="changeState(\'' + id + '\',3)"data-row=' + id + ' data-index=' + index + '>确认发货</button>';

    return res;
}

$(function () {

    var sw = [];
    $(".js-switch").each(function (i, e) {
        sw[i] = new Switchery(e, {color: "#1AB394"})
    })
    $(window).resize(function () {
        $('#mytable').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })
    //生成用户数据
    $('#mytable').bootstrapTable({
        method: 'get',
        url: "/admin/order/list",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: queryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 50,//单页记录数
        pageList: [50, 100, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        detailView: true,//父子表
        onExpandRow: function (index, row, $detail) {
            initSubTable(index, row, $detail);
        },
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: false,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '商品ID',
                visible: false,
                field: 'gid'
            },
            {
                title: '订单商品',
                visible: true,
                field: 'goodsName'
            },
            {
                title: '买家',
                field: 'linkman',
                width: 120,
            },
            {
                title: '买家电话',
                field: 'phone',
                width: 100,
            },
            {
                title: '买家地址',
                field: 'address'
            },
            {
                title: '数量',
                field: 'goodsNumber',
                width: 50
            },
            // {
            //     title: '订单编号',
            //     visible: true,
            //     field: 'orderNo'
            // },
            {
                title: '总价',
                field: 'total',
                width: 60
            },
            {
                title: '商品价',
                field: 'prices',
                width: 60
            },
            {
                title: '运费',
                field: 'yunfei',
                width: 60
            },

            // {
            //     title: '支付方式',
            //     field: 'payType',
            //     formatter: "payTypeFormatter"
            // },
            {
                title: '实付',
                field: 'realpay',
                width: 60
            },
            {
                title: '订单时间',
                field: 'createtime',
                formatter: "timeFormatter",
                width: 150
            },
            {
                title: '状态',
                field: 'status',
                width: 80,
                formatter: "statusFormatter"
            },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                formatter: orderActionFormatter
            }
        ],
        locale: 'zh-CN'//中文支持,
    })

    //请求服务数据时所传参数
    function initSubTable(index, row, $detail) {
        console.log(index)
        console.log(row)
        console.log($detail)
        var oid = row.id;
        console.log(row)
        console.log("----------------------------------initSubTable oid=" + oid)
        var cur_table = $detail.html('<table></table>').find('table');
        $(cur_table).bootstrapTable({
            url: "/admin/ordergoods/list",
            method: 'get',
            queryParams: {oid: oid, offset: 0, limit: 20},
            // ajaxOptions: {oid: oid},
            clickToSelect: true,
            detailView: false,//父子表
            uniqueId: "id",
            dataField: "records",
            queryParamsType: 'limit',
            locale: 'zh-CN',//中文支持,
            sidePagination: 'server',
            pagination: false,//是否分页
            columns: [{
                checkbox: false
            }, {
                title: 'ID',
                field: 'id',
                visible: false
            },
                {
                    title: '订单id',
                    field: 'oid',
                    visible: false
                },
                {
                    title: '订单编号',
                    visible: false,
                    field: 'orderNo'
                },
                {
                    title: '商品id',
                    field: 'gid',
                    visible: false
                },
                {
                    title: '商品名称',
                    field: 'goodsName'
                },
                {
                    title: '商品规格',
                    field: 'spec'
                },
                {
                    title: '商品图',
                    field: 'pic',
                    formatter: "imgFormatter"
                },
                {
                    title: '商品标价原价',
                    field: 'price'
                },
                {
                    title: '实际售价',
                    field: 'saleprice'
                },
                {
                    title: '购买数量',
                    field: 'number'
                },
                {
                    title: '总价',
                    field: 'total'
                },
                {
                    title: '操作',
                    field: 'Attribute',
                    align: 'center',
                    formatter: goodActionFormatter
                }]
        })
    }

    //请求服务数据时所传参数
    function queryParams(params) {
        var p = {
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order,
            search: $('#search').val(),
            type: $('#qtype').find("option:selected").val(),
            status: $('#qstatus').find("option:selected").val()
        }
        console.log(p)
        return p;
    }

    $('#search_btn').click(function () {
        var params = {
            search: $('#search').val(),
            ts: new Date().getTime()
        };
        console.log("===============search_btn click");
        console.log(params);
        $('#mytable').bootstrapTable('refresh', params);
    })

    /*
     * 验证错误提示信息高亮
     */
    $.validator.setDefaults({
        highlight: function (e) {
            $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
        }, success: function (e) {
            e.closest(".form-group").removeClass("has-error").addClass("has-success")
        }, errorElement: "span", errorPlacement: function (e, r) {
            e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
        }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
    }), $("#aform").validate(), $("#mform").validate();
})

function checkAdd() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });

    if ($("#hidpic").attr("required") == "required"
        && $("#hidpic").val() == "") {
        swal({title: "请上传图片", text: "", type: "warning"})
        return false;
    }
    return true;
}

function checkModify() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });

    if ($("#hidpic2").attr("required") == "required"
        && $("#hidpic2").val() == "") {
        swal({title: "请上传图片", text: "", type: "warning"})
        return false;
    }
    return true;
}